/**
 * 缓存管理器模块
 * 用于管理应用程序中的各种数据缓存
 */

// 缓存配置
const CACHE_TTL = 5 * 60 * 1000; // 缓存有效期(毫秒): 5分钟

// 缓存存储
const cache = {
  journals: {
    data: null,
    timestamp: 0,
    publishers: null,
    publishersTimestamp: 0,
    categories: null,
    categoriesTimestamp: 0
  },
  books: {
    data: null,
    timestamp: 0,
    publishers: null,
    publishersTimestamp: 0,
    categories: null,
    categoriesTimestamp: 0
  },
  search: {
    data: null,
    timestamp: 0
  }
};

/**
 * 获取缓存数据
 * @param {string} cacheKey - 缓存键名(journals/books/search)
 * @param {string} dataType - 数据类型(data/publishers/categories)
 * @returns {any|null} - 缓存数据或null(如果缓存无效)
 */
function getCache(cacheKey, dataType = 'data') {
  if (!cache[cacheKey]) return null;

  const now = Date.now();
  const timestampKey = dataType === 'data' ? 'timestamp' : `${dataType}Timestamp`;

  if (cache[cacheKey][dataType] && now - cache[cacheKey][timestampKey] < CACHE_TTL) {
    console.log(`[Cache] Hit for ${cacheKey}.${dataType}`);
    return cache[cacheKey][dataType];
  }

  console.log(`[Cache] Miss for ${cacheKey}.${dataType}`);
  return null;
}

/**
 * 设置缓存数据
 * @param {string} cacheKey - 缓存键名
 * @param {string} dataType - 数据类型
 * @param {any} data - 要缓存的数据
 */
function setCache(cacheKey, dataType = 'data', data) {
  if (!cache[cacheKey]) return;

  const timestampKey = dataType === 'data' ? 'timestamp' : `${dataType}Timestamp`;

  cache[cacheKey][dataType] = data;
  cache[cacheKey][timestampKey] = Date.now();
  console.log(`[Cache] Updated ${cacheKey}.${dataType}`);
}

/**
 * 清除指定缓存
 * @param {string} cacheKey - 缓存键名
 * @param {string} dataType - 数据类型，为null时清除所有相关缓存
 */
function clearCache(cacheKey, dataType = null) {
  if (!cache[cacheKey]) return;

  if (dataType) {
    const timestampKey = dataType === 'data' ? 'timestamp' : `${dataType}Timestamp`;
    cache[cacheKey][dataType] = null;
    cache[cacheKey][timestampKey] = 0;
    console.log(`[Cache] Cleared ${cacheKey}.${dataType}`);
  } else {
    // 清除该键下所有缓存
    Object.keys(cache[cacheKey]).forEach(key => {
      if (!key.includes('Timestamp')) {
        cache[cacheKey][key] = null;
        cache[cacheKey][`${key}Timestamp`] = 0;
      }
    });
    console.log(`[Cache] Cleared all ${cacheKey} caches`);
  }
}

/**
 * 清除所有缓存
 */
function clearAllCache() {
  Object.keys(cache).forEach(key => clearCache(key));
  console.log('[Cache] Cleared all caches');
}

/**
 * 获取缓存状态信息
 * @returns {Object} 缓存状态信息
 */
function getCacheStatus() {
  const status = {};

  Object.keys(cache).forEach(cacheKey => {
    status[cacheKey] = {};

    Object.keys(cache[cacheKey]).forEach(key => {
      if (!key.includes('Timestamp')) {
        const timestampKey = key === 'data' ? 'timestamp' : `${key}Timestamp`;
        const timestamp = cache[cacheKey][timestampKey];
        const age = timestamp ? Math.round((Date.now() - timestamp) / 1000) : null;

        status[cacheKey][key] = {
          exists: cache[cacheKey][key] !== null,
          age: age ? `${age}s` : 'N/A',
          valid: age !== null && age * 1000 < CACHE_TTL
        };
      }
    });
  });

  return status;
}

module.exports = {
  getCache,
  setCache,
  clearCache,
  clearAllCache,
  getCacheStatus
}; 
